<template>
  <div class="bone-density-container">
    <el-row :gutter="20">
      <!-- 左侧PDF预览区域 -->
      <el-col :span="12">
        <div class="pdf-viewer-container">
          <div class="pdf-controls">
            <el-button-group>
              <el-button size="small" type="primary" @click="prevFile" :disabled="currentFileIndex === 0">
                上一个文件
              </el-button>
              <el-button size="small" type="success" @click="nextFile"
                         :disabled="currentFileIndex === pdfFiles.length - 1">
                下一个文件
              </el-button>
            </el-button-group>
            <!-- 添加删除按钮 -->
            <el-button
              size="small"
              type="danger"
              @click="deleteFile"
              :disabled="!pdfFiles.length">
              删除当前文件
            </el-button>
            <!-- 切换PDF/TXT按钮 -->
            <el-button size="small" type="primary" @click="toggleViewMode();loadTxtFile()" :disabled="!pdfFiles.length"
                       class="toggle-btn">
              {{ viewMode === 'pdf' ? '切换至TXT' : '切换至PDF' }}
            </el-button>
            <!--          上传PDF文件按钮-->
            <el-button size="small" type="primary" @click="triggerFileUpload" class="upload-btn">
              上传PDF文件
            </el-button>
            <input type="file" ref="fileInput" @change="handleFileUpload" multiple accept=".pdf" style="display: none">
          </div>
          <!--          以下展示PDF和TXT文件-->
          <div class="pdf-viewer-wrapper">
            <div v-if="viewMode === 'pdf'">
              <pdf v-for="page in numPages" :key="page" :src="pdfUrl" :page="page" class="pdf-page"
                   v-if="pdfFiles.length"></pdf>
              <!--            切换页数-->
              <div class="page-controls" v-if="pdfFiles.length">
                <el-button size="mini" @click="prevPage" :disabled="currentPage === 1">上一页</el-button>
                <span>第 {{ currentPage }} 页 / 共 {{ numPages }} 页</span>
                <el-button size="mini" @click="nextPage" :disabled="currentPage === numPages">下一页</el-button>
              </div>
            </div>
            <!-- TXT视图 -->
            <div v-if="viewMode === 'txt'" class="txt-viewer">
              <div v-if="fileContent" class="file-content"></div>
              <h3>文件内容:</h3>
              <pre>{{ fileContent }}</pre>
            </div>
          </div>
        </div>
      </el-col>
      <!-- 右侧表单区域 -->
      <el-col :span="12">
        <div class="report-form-container">
          <div class="form-header">
            <h1 class="form-title">骨密度策略报告</h1>
            <div class="form-actions" style="text-align: right">
              <el-button v-if="editMode" type="success" @click="saveForm" icon="el-icon-check">
                保存
              </el-button>
              <!--              <el-button v-else type="primary" @click="editForm" icon="el-icon-edit">-->
              <!--                编辑-->
              <!--              </el-button>-->
              <el-button type="primary" @click="runStrategy">执行策略</el-button>
              <el-button type="danger" @click="exitPage">退出页面</el-button>
            </div>
          </div>

          <el-form ref="reportForm" :model="reportData" :rules="formRules" label-width="100px" class="report-form k-form">
            <el-form-item label="基本信息" class="section-title"></el-form-item>
            <!-- 列标题行 -->
            <el-row :gutter="20" class="header-row">
              <el-col :span="12">
                <div class="column-title">策略</div>
              </el-col>
              <el-col :span="12">
                <div class="column-title">数据</div>
              </el-col>
            </el-row>
            <!--            姓名-->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="姓名">
                  <el-input v-model="reportData.name" :readonly="!editMode" placeholder="点击+号添加姓名策略">
                  </el-input>
                  <i class="expand-btn el-icon-circle-plus-outline" @click="openExpandDialog('name', '姓名',false)"></i>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :class="{'is-error': !runStrategyData.name && dataFetched}">
                  <el-input v-model="runStrategyData.name"
                            :class="{'error-border': !runStrategyData.name && dataFetched}"></el-input>
                  <div class="error-tip" v-if="!runStrategyData.name && dataFetched" >
                    警告：后端返回的姓名为空，请检查数据源！
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <!--          年龄-->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="年龄">
                  <el-input v-model="reportData.age" :readonly="!editMode" placeholder="点击+号添加年龄策略"></el-input>
                  <i class="expand-btn el-icon-circle-plus-outline" @click="openExpandDialog('age', '年龄',false)"></i>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :class="{'is-error': !runStrategyData.age && dataFetched}">
                  <el-input v-model="runStrategyData.age"
                            :class="{'error-border': !runStrategyData.age && dataFetched}"></el-input>
                  <div class="error-tip" v-if="!runStrategyData.age && dataFetched" >
                    警告：后端返回的年龄为空，请检查数据源！
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <!--性别-->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="性别">
                  <el-input v-model="reportData.gender" :readonly="!editMode"
                            placeholder="点击+号添加性别策略"></el-input>
                  <i class="expand-btn el-icon-circle-plus-outline"
                     @click="openExpandDialog('gender', '性别',false)"></i>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :class="{'error-border': !runStrategyData.gender && dataFetched}">
                  <el-input v-model="runStrategyData.gender"
                            :class="{'error-border': !runStrategyData.gender && dataFetched}"></el-input>
                  <div class="error-tip" v-if="!runStrategyData.gender && dataFetched" >
                    警告：后端返回的性别为空，请检查数据源！
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <!--            床号-->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="床号">
                  <el-input v-model="reportData.bedNumber" :readonly="!editMode"
                            placeholder="点击+号添加床号策略"></el-input>
                  <i class="expand-btn el-icon-circle-plus-outline"
                     @click="openExpandDialog('bedNumber', '床号',false)"></i>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-input v-model="runStrategyData.bedNumber"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!--            门诊/住院号-->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="门诊/住院号">
                  <el-input v-model="reportData.patientNumber" :readonly="!editMode"
                            placeholder="点击+号添加门诊/住院号策略"></el-input>
                  <i class="expand-btn el-icon-circle-plus-outline"
                     @click="openExpandDialog('patientNumber', '门诊/住院号',false)"></i>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-input v-model="runStrategyData.patientNumber"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!--            申请科室-->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="申请科室">
                  <el-input v-model="reportData.department" :readonly="!editMode"
                            placeholder="点击+号添加申请科室策略"></el-input>
                  <i class="expand-btn el-icon-circle-plus-outline"
                     @click="openExpandDialog('department', '申请科室',false)"></i>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-input v-model="runStrategyData.department"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!--              检查医生-->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="检查医生">
                  <el-input v-model="reportData.doctor" :readonly="!editMode"
                            placeholder="点击+号添加检查医生策略"></el-input>
                  <i class="expand-btn el-icon-circle-plus-outline"
                     @click="openExpandDialog('doctor', '检查医生',false)"></i>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-input v-model="runStrategyData.doctor"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!--              检查时间-->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="检查时间">
                  <el-input v-model="reportData.examTime" :readonly="!editMode"
                            placeholder="点击+号添加检查时间策略"></el-input>
                  <i class="expand-btn el-icon-circle-plus-outline"
                     @click="openExpandDialog('examTime', '检查时间',false)"></i>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-input v-model="runStrategyData.examTime"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!--       检查所见-->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="检查所见">
                  <el-input type="textarea" :rows="6" v-model="reportData.findings" :readonly="!editMode"
                            placeholder="点击+号添加检查所见策略"></el-input>
                  <i class="expand-btn el-icon-circle-plus-outline"
                     @click="openExpandDialog('findings', '检查所见', false)"></i>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-input
                    type="textarea"
                    :rows="6"
                    v-model="runStrategyData.findings"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!--              报告结论-->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="报告结论">
                  <el-input type="textarea" :rows="6" v-model="reportData.conclusion" :readonly="!editMode"
                            placeholder="点击+号添加报告结论策略"></el-input>
                  <i class="expand-btn el-icon-circle-plus-outline"
                     @click="openExpandDialog('conclusion', '报告结论', false)"></i>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-input
                    type="textarea"
                    :rows="6"
                    v-model="runStrategyData.conclusion"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!--   审核医生-->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="审核医生">
                  <el-input v-model="reportData.reviewDoctor" :readonly="!editMode"
                            placeholder="点击+号添加审核医生策略"></el-input>
                  <i class="expand-btn el-icon-circle-plus-outline"
                     @click="openExpandDialog('reviewDoctor', '审核医生',false)"></i>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-input v-model="runStrategyData.reviewDoctor"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!--             发布时间-->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="发布时间">
                  <el-input v-model="reportData.publishTime" :readonly="!editMode"
                            placeholder="点击+号添加发布时间策略"></el-input>
                  <i class="expand-btn el-icon-circle-plus-outline"
                     @click="openExpandDialog('publishTime', '发布时间',false)"></i>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-input v-model="runStrategyData.publishTime"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-col>
      <!-- 扩展编辑对话框 -->
      <el-dialog
        :title="'编辑' + expandDialog.title"
        :visible.sync="expandDialog.visible"
        class="fullscreen-dialog"
        :append-to-body="true"
        width="50%">
        <div v-if="expandDialog.isTextarea">
          <el-input
            type="textarea"
            :autosize="{ minRows: 8, maxRows: 12 }"
            v-model="expandDialog.value"
            class="fullscreen-textarea"
            placeholder="请输入内容">
          </el-input>
        </div>
        <div v-else>
          <el-input
            v-model="newItemValue"
            :placeholder="'请输入' + expandDialog.title"
            @keyup.enter.native="addItemToList"
            style="width: 70%; margin-right: 10px;">
          </el-input>
          <el-button type="primary" @click="addItemToList">添加</el-button>
          <div class="name-list-container">
            <p style="margin: 15px 0 5px;">已添加的内容: </p>
            <div v-for="(item, index) in itemList" :key="index" class="name-list-item">
              <div class="name-list-item-content">{{ item }}</div>
              <i class="el-icon-close name-list-item-remove" @click="removeItemFromList(index)"></i>
            </div>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
        <el-button @click="expandDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmExpandEdit">确定</el-button>
      </span>
      </el-dialog>
    </el-row>
  </div>
</template>

<script>
import pdf from 'vue-pdf'
import axios from "axios";

import {
  selectPdfUrlList,
  selectStrategyDetail,
  uploadFiles,
  deletePdfUrl,
  saveStrategy,
  runStrategyReport,
  selectFileData,
} from "@/api/analysis/report";

export default {
  props: {
    strategyId: {
      type: Number,
      required: true
    }
  },
  components: {
    pdf
  },
  data() {
    return {
      dataFetched: false,
      viewMode: 'pdf', // 默认
      loadingTxt: false, // 加载TXT状态
      loading: false, // 加载状态
      pdfFiles: [], // 存储上传的PDF文件
      currentFileIndex: -1, // 当前显示的PDF文件索引
      pdfUrl: '', // 当前显示的PDF文件URL
      txtUrl: '', // 当前显示的TXT文件URL
      fileContent: '', // 存放实际文件内容
      numPages: 0, // 当前PDF的总页数
      currentPage: 1, // 当前显示的PDF页码
      newItemValue: '', // 新增记录输入框值
      itemList: [], // 新增记录列表
      // 新增记录的弹框
      expandDialog: {
        visible: false,
        title: '',
        field: '',
        value: '',
        isTextarea: false
      },
      // 策略报告数据
      reportData: {
        name: '',
        age: '',
        gender: '',
        bedNumber: '',
        patientNumber: '',
        department: '',
        doctor: '',
        examTime: '',
        findings: '',
        conclusion: '',
        reviewDoctor: '',
        publishTime: ''
      },
      // 执行策略后的结果数据
      // 策略报告数据
      runStrategyData: {
        name: '',
        age: '',
        gender: '',
        bedNumber: '',
        patientNumber: '',
        department: '',
        doctor: '',
        examTime: '',
        findings: '',
        conclusion: '',
        reviewDoctor: '',
        publishTime: ''
      },
      fileListLoading: false,//新增文件列表加载状态
      removeId: 0,
      editMode: true, // 编辑模式
      strategyList: [], // 策略列表
      brandId: null,
      checkId: null,
      fileId: null,
    }
  },
  created() {
    this.parseRouteQuery()
    this.fetchPdfFiles();
    this.fetchReportData();
    // this.fetchReportData();
    this.acquireStrategyDeatil()
    //this.loadTxtFile()
  },
  methods: {
    //退出页面
    exitPage() {
      let routePath = '/analysis/report';
      this.$router.push({
        path: routePath,
      });
    },
    //通过从后台获取txt解析文件
    async loadTxtFile() {
      try {
        const response = await axios.get(this.txtUrl);
        // 添加响应状态检查
        this.fileContent = await response.data;
      } catch (error) {
        console.error('加载文件失败:', error);
        this.fileContent = 'pdf文件无对应的txt文件';
      }
    },
    // 打开记录展示对话框
    // 弹出框
    openExpandDialog(field, title, isTextarea) {
      this.expandDialog.title = title;
      this.expandDialog.field = field;
      this.expandDialog.isTextarea = isTextarea;
      this.expandDialog.value = this.reportData[field];
      this.expandDialog.visible = true;
      if (!isTextarea) {
        this.itemList = this.reportData[field] ? this.reportData[field].split(',').filter(item => item.trim()) : [];
        this.newItemValue = '';
      }
    },
    addItemToList() {
      if (this.newItemValue.trim()) {
        this.itemList.push(this.newItemValue.trim());
        this.newItemValue = '';
      }
    },
    removeItemFromList(index) {
      this.itemList.splice(index, 1);
    },
    confirmExpandEdit() {
      if (this.expandDialog.isTextarea) {
        this.reportData[this.expandDialog.field] = this.expandDialog.value;
      } else {
        this.reportData[this.expandDialog.field] = this.itemList.join(',');
      }
      this.expandDialog.visible = false;
    },
    // 刷新页面
    refreshPage() {
      this.fetchPdfFiles()
      this.fetchReportData()
    },
    // 执行策略
    runStrategy() {
      const {brandId, checkId, reportId} = this.$route.query;
      // 这里替换为实际的API调用
      runStrategyReport(brandId, checkId, reportId, this.fileId).then(response => {
        if (response.code === 200 && response.data) {
          this.runStrategyData = response.data;
          this.$message.success('策略执行成功，正在获取报告数据...');
          this.fetchPdfFiles();
          this.loadTxtFile();
          this.dataFetched = true;
        } else {
          this.$message.error(response.msg || '策略执行出错');
        }
      }).catch(error => {
        this.$message.error('获取策略失败')
      })
    },

    // 从后端获取执行策略后的结果数据
    fetchReportData() {
      try {
        const {reportId} = this.$route.query;
        const fileId = 0;
        // 这里替换为实际的API调用
        selectFileData(reportId, fileId).then(response => {
          if (response.code === 200 && response.data) {
            this.runStrategyData = response.data;
          } else {
            this.$message.error(response.msg || '数据解析出错');
          }
        })
      } catch (error) {
        console.error('获取报告数据失败:', error)
        this.$message.error('获取报告数据失败')
      }
    },
    // 获取到brandId和checkId数值
    parseRouteQuery() {
      const {brandId, checkId} = this.$route.query
      this.brandId = brandId
      this.checkId = checkId
    },
    // 获取到策略数据
    acquireStrategyDeatil() {
      // const {brandId, checkId} = this.$route.query;
      this.loading = true;
      selectStrategyDetail(this.brandId, this.checkId).then(response => {
        if (!response.data || response.data.length === 0) {
          console.log('暂无策略数据');
          return;
        }
        // 初始化报告数据
        const reportData = {
          name: '',
          age: '',
          gender: '',
          bedNumber: '',
          patientNumber: '',
          department: '',
          doctor: '',
          examTime: '',
          findings: '',
          conclusion: '',
          reviewDoctor: '',
          publishTime: '',
          brandId: '',
          checkId: '',
        };
        // 将后端数组转换为前端需要的对象格式
        this.strategyList = response.data;
        // 将策略数据映射到表单数据
        this.mapStrategyToForm();
        this.loading = false;
      }).catch(error => {
        console.error('获取策略数据失败:', error);
        this.loading = false;
      });
    },

    // 将策略数据映射到表单
    mapStrategyToForm() {
      this.strategyList.forEach(item => {
        const key = item.keyName.trim(); // 去除可能的空格
        if (this.reportData.hasOwnProperty(key)) {
          // 处理特殊格式的valueName
          let value = item.valueName;
          if (value.startsWith('"') && value.endsWith('"')) {
            value = value.substring(1, value.length - 1);
          }
          this.reportData[key] = value;
        }
      });
    },

    // 进入编辑模式
    editForm() {
      this.editMode = true;
    },

    // 保存表单
    saveForm() {
      try {
        // 获取路由参数
        const {brandId, checkId} = this.$route.query;
        const formData = this.prepareSubmitData();
        console.log('提交的表单数据:', formData);
        saveStrategy(formData, brandId, checkId).then(response => {
          if (response.code === 200) {
            // this.editMode = false;
            this.$message.success('表单保存成功');
          } else {
            this.$message.error(response.data.message);
          }
        })
      } catch (error) {
        console.error('保存表单失败:', error);
        this.$message.error('保存表单失败: ${error.message}');
      }
    },

    // 准备提交数据
    prepareSubmitData() {
      return Object.keys(this.reportData).map(key => {
        const strategyItem = this.strategyList.find(item => item.keyName.trim() === key);
        return {
          keyName: key,
          valueName: this.reportData[key],
          titleName: strategyItem ? strategyItem.titleName : '',
          isCustom: strategyItem ? strategyItem.isCustom : 0,
          strategyId: strategyItem ? strategyItem.strategyId : null
        };
      });
    },
    // 触发文件上传
    triggerFileUpload() {
      this.$refs.fileInput.click()
    },
    // 优化后的文件上传处理
    handleFileUpload(event) {
      const files = Array.from(event.target.files);
      if (files.length === 0) return;
      // 过滤非PDF文件
      const pdfFiles = files.filter(file => file.type === 'application/pdf');
      if (pdfFiles.length === 0) {
        this.$message.error('请上传PDF文件');
        return;
      }
      // 添加到PDF文件列表
      this.pdfFiles = [...this.pdfFiles, ...pdfFiles]
      // 如果是第一个文件，直接显示
      if (this.currentFileIndex === -1 && this.pdfFiles.length > 0) {
        this.currentFileIndex = 0
        const fileId = this.pdfFiles[this.currentFileIndex].fileId;
        this.fileId = fileId
        this.loadPdfFile(this.pdfFiles[0])
      }
      // 获取路由参数
      const {brandId, checkId, reportId} = this.$route.query;
      // 准备FormData
      const formData = new FormData();
      // 添加文件
      pdfFiles.forEach(file => {
        formData.append('files', file);
      });
      // 添加其他参数
      if (brandId) formData.append('brandId', brandId);
      if (reportId) formData.append('reportId', reportId);
      if (checkId) formData.append('checkId', checkId);
      // 显示加载状态
      this.loading = true;
      // 调用后端接口
      uploadFiles(pdfFiles, brandId, reportId, checkId).then(response => {
        if (response.code === 200) {
          this.$message.success(`成功上传${pdfFiles.length}个PDF文件`);
          //this.fetchPdfFiles(); // 更新文件列表
          this.runStrategyData = []
          this.fetchPdfFiles()
        } else {
          this.$message.error(response.msg || '文件上传失败');
        }
      }).catch(error => {
        this.$message.error('上传过程中发生错误');
        console.error('上传错误:', error);
      }).finally(() => {
        this.loading = false;
      })
      this.fetchReportData()
    },

// 修改fetchPdfFiles方法， 从数据库中获取PDF文件列表
    fetchPdfFiles() {
      const {reportId} = this.$route.query;
      this.fileListLoading = true;
      selectPdfUrlList(reportId).then(response => {
        if (response.code === 200 && response.data) {
          this.pdfFiles = response.data;
          // 自动选择最新上传的文件
          const latestFile = this.pdfFiles.find(file => file.isLatest) || this.pdfFiles[0];
          if (latestFile) {
            this.currentFileIndex = this.pdfFiles.indexOf(latestFile);
            // 获取fileId
            const fileId = this.pdfFiles[this.currentFileIndex].fileId;
            this.fileId = fileId
            // 获取txt文件
            const txtPath = this.pdfFiles[this.currentFileIndex].txtUrl;
            this.txtUrl = txtPath
            this.loadPdfFile(latestFile);
          }
        } else {
          this.$message.error(response.msg || '文件获取失败');
        }
      }).catch(error => {
        console.error("获取文件列表出错：", error);
        this.$message.error("获取文件列表出错");
      }).finally(() => {
        this.fileListLoading = false;
      })
    },
    // 删除PDF文件
    // 添加删除方法
    deleteFile() {
      this.$confirm('确定要删除这个文件吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return deletePdfUrl(this.fileId).then(response => {
          if (response.code === 200) {
            this.$message.success('文件删除成功');
            this.fetchPdfFiles(); // 刷新文件列表
          } else {
            this.$message.error(response.msg || '文件删除失败');
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 重置PDF查看器状态
    resetPdfViewer() {
      this.currentFileIndex = -1;
      this.pdfUrl = '';
      this.numPages = 0;
      this.currentPage = 1;
    },

    // 修改loadPdfFile方法
    loadPdfFile(file) {
      if (!file || !file.fileUrl) return;

      this.loading = true;
      // 如果是URL直接使用
      if (file.fileUrl.startsWith('http')) {
        this.pdfUrl = file.fileUrl;
        this.removeId = file.fileId;
      }
      // 如果是本地文件
      else if (file instanceof File) {
        const fileReader = new FileReader();
        fileReader.onload = () => {
          this.pdfUrl = fileReader.result;
          this.getPdfPageCount();
        };
        fileReader.readAsDataURL(file);
        return;
      }

      this.getPdfPageCount();
    },

    getPdfPageCount() {
      const loadingTask = pdf.createLoadingTask(this.pdfUrl);
      loadingTask.promise.then(pdf => {
        this.numPages = pdf.numPages;
        this.currentPage = 1;
      }).catch(err => {
        console.error('PDF加载错误:', err);
        this.$message.error('PDF文件加载失败');
      }).finally(() => {
        this.loading = false;
      });
    },
    // 上一个PDF文件
    prevFile() {
      if (this.currentFileIndex > 0) {
        this.currentFileIndex--
        this.loadPdfFile(this.pdfFiles[this.currentFileIndex])
        // 获取fileId
        const fileId = this.pdfFiles[this.currentFileIndex].fileId;
        this.fileId = fileId
        // 获取txt文件
        const txtPath = this.pdfFiles[this.currentFileIndex].txtUrl;
        this.txtUrl = txtPath
        console.log("切换到文件的ID: " + fileId)
        this.nextReportData(fileId)
      }
    },

    // 下一个PDF文件
    nextFile() {
      if (this.currentFileIndex < this.pdfFiles.length - 1) {
        this.currentFileIndex++
        // 获取fileId
        const fileId = this.pdfFiles[this.currentFileIndex].fileId;
        this.fileId = fileId
        // 获取txt文件
        const txtPath = this.pdfFiles[this.currentFileIndex].txtUrl;
        this.txtUrl = txtPath
        console.log("切换到文件的ID: " + fileId)
        this.loadPdfFile(this.pdfFiles[this.currentFileIndex])
        this.nextReportData(fileId)
      }
    },
    toggleViewMode() {
      this.viewMode = this.viewMode === 'pdf' ? 'txt' : 'pdf';
    },
    // 从后端获取执行策略后的结果数据
    nextReportData(fileId) {
      try {
        const {reportId} = this.$route.query;
        // 这里替换为实际的API调用
        selectFileData(reportId, fileId).then(response => {
          if (response.code === 200 && response.data) {
            this.runStrategyData = response.data;
          } else {
            this.$message.error(response.msg || '数据解析出错');
          }
        })
      } catch (error) {
        console.error('获取报告数据失败:', error)
        this.$message.error('获取报告数据失败')
      }
    },
    // 上一页
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--
      }
    },
    // 下一页
    nextPage() {
      if (this.currentPage < this.numPages) {
        this.currentPage++
      }
    },
    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
  }
}
</script>

<style scoped>
.bone-density-container {
  padding: 20px;
  background-color: #fff;
  height: calc(100vh - 40px);
  overflow-y: auto;
}

.pdf-viewer-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  height: calc(100vh - 100px);
  display: flex;
  flex-direction: column;
}

.pdf-controls {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-btn {
  margin-left: 10px;
}

.pdf-viewer-wrapper {
  flex: 1;
  overflow-y: auto;
  position: relative;
}

.pdf-page {
  margin-bottom: 10px;
  border: 1px solid #ddd;
}

.page-controls {
  margin-top: 10px;
  text-align: center;
}

.report-form-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  height: calc(100vh - 100px);
  overflow-y: auto;
}

.form-title {
  text-align: center;
  margin-bottom: 20px;
  color: #409EFF;
}

.section-title {
  font-weight: bold;
  margin-top: 10px;
  margin-bottom: 5px;
}

.report-form {
  margin-top: 20px;
}

.header-row {
  margin-bottom: 45px;
  text-align: center;
  color: darkblue;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}

.fullscreen-textarea {
  width: 100%;
}

.fullscreen-dialog .el-dialog {
  width: 95% !important;
  max-width: 1300px;
}

.report-form-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.form-title {
  color: #409EFF;
  margin: 0;
}

.header-row {
  margin-bottom: 20px;
  font-weight: bold;
  color: #409EFF;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.expand-btn {
  margin-left: 10px;
  font-size: 16px;
  color: #409EFF;
  cursor: pointer;
}

.display-btn {
  margin-left: 5px;
  font-size: 16px;
  color: #67C23A;
  cursor: pointer;
}

.fullscreen-dialog {
  min-width: 60%;
}

.fullscreen-textarea {
  width: 100%;
}

.record-item {
  padding: 10px;
  margin-bottom: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.record-display-dialog .el-dialog__body {
  max-height: 60vh;
  overflow-y: auto;
}

.report-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.report-form-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.form-title {
  margin: 0;
  color: #303133;
}

.report-form {
  margin-top: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 15px !important;
}

.header-row {
  margin-bottom: 15px;
}

.column-title {
  font-weight: bold;
  color: #409EFF;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.expand-btn {
  margin-left: 10px;
  font-size: 16px;
  color: #409EFF;
  cursor: pointer;
}

.el-form-item {
  position: relative;
  margin-bottom: 15px;
}

.name-list-container {
  margin-top: 15px;
  max-height: 300px;
  overflow-y: auto;
}

.name-list-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.name-list-item-content {
  flex: 1;
}

.name-list-item-remove {
  color: #F56C6C;
  cursor: pointer;
}

.dialog-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.fullscreen-textarea {
  width: 100%;
}

.text-display pre {
  font-size: 20px; /* 调整字体大小 */
  line-height: 1.5; /* 调整行高 */
  white-space: pre-wrap; /* 保留空白符序列，但正常换行 */
  word-wrap: break-word; /* 允许长单词换行 */
}

.file-content {
  /*overflow-x: auto; !* 添加水平滚动条 *!*/
  /*white-space: pre; !* 保留空白和换行 *!*/
  /*font-family: monospace; !* 使用等宽字体 *!*/
  /*tab-size: 4; !* 设置制表符宽度 *!*/

  font-family: monospace; /* 确保空格对齐 */
  overflow-x: auto; /* 允许横向滚动 */
  white-space: nowrap; /* 禁止换行 */
}

/*pre {margin: 0;*/
/*  padding: 10px;*/
/*  background-color: #f5f5f5;*/
/*  border-radius: 4px;*/
/*}*/

.k-form {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/*.el-input.is-error .el-input__inner {*/
/*  border-color: #f56c6c;*/
/*}*/


</style>
